#include "socket_tcp.h"
#include "iostream"
Socket_tcp::Socket_tcp(const string& ip_addr,int l_port,int l_link_max,File_wr* l_file_opertion)
:link_max(l_link_max)
,file_opertion(l_file_opertion)  {

    int opt = 1;
    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket creation failed");
        objcreat_errflag = 1;
        //return -1;
    }
   // memcpy(ip_addr,l_ip_addr,sizeof(l_ip_addr));
    port = l_port;
    link_max = l_link_max;
    link_success = 0;
    objcreat_errflag = 0;
        // 设置套接字选项，允许端口重用
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("Setsockopt failed");
        objcreat_errflag = 1;
        //return -1;
    }
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(port);
    if(inet_pton(AF_INET,ip_addr.c_str(),&address.sin_addr)<=0)
    {
        perror("inet_pton failed");
        objcreat_errflag = 1;
    }
    // 绑定套接字到地址
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
        perror("Bind failed");
        objcreat_errflag = 1;
        //return -1;
    }

    // 开始监听，最大连接数为5
    if (listen(server_fd, link_max) < 0) {
        perror("Listen failed");
        objcreat_errflag = 1;
        //return -1;
    }
}

int Socket_tcp::wait_tcp_link(void)
{
    //int new_socket;
    int addr_len = 0;
    printf("Waiting for connection...\n");
    if(objcreat_errflag == 1)
    {
      return -1;

    }
    addr_len = sizeof(address);
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addr_len))<0) {
                perror("Accept failed");
                return -1;
    }
    link_success = 1;
    printf("Connection accepted\n");
    return 0;
}

int Socket_tcp::s_read(char* buffer,int len)
{
    if(objcreat_errflag == 1)
    {
      return -1;
    }
    file_opertion->s_read(buffer,len,new_socket);
    return 0;
}

int Socket_tcp::s_write(char* buffer,int len)
{
    if(objcreat_errflag == 1)
    {
      return -1;
    }
    file_opertion->s_write(buffer,len,new_socket);
    return 0;
}
Socket_tcp::~Socket_tcp()
{
    
    close(server_fd);
    link_success = 0;
    cout << "byebye" << endl;
}